package com.streamer.app.adapter

import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.streamer.app.R
import com.streamer.app.bean.MessageBean

class ChatAdapter(
    private val messages: MutableList<MessageBean>
) : RecyclerView.Adapter<ChatAdapter.MessageVH>() {

    class MessageVH(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val ivAvatar: ImageView = itemView.findViewById(R.id.iv_avatar)
        val tvName: TextView = itemView.findViewById(R.id.tv_name)
        val tvContent: TextView = itemView.findViewById(R.id.tv_content)
        val tvTimestamp: TextView = itemView.findViewById(R.id.tv_timestamp)
        val tvRoleTag: TextView = itemView.findViewById(R.id.tv_role_tag)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MessageVH {
        val v =
            LayoutInflater.from(parent.context).inflate(R.layout.item_chat_message, parent, false)
        return MessageVH(v)
    }

    override fun onBindViewHolder(holder: MessageVH, position: Int) {
        val item = messages[position]
        holder.tvName.text = item.senderName
        holder.tvContent.text = item.content
        val sdf = java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault())
        val formatted1 = sdf.format(java.util.Date(item.senderAt * 1000L))
        when (item.userType) {
            1 -> {
                holder.tvRoleTag.text = "助教"

            }

            2 -> {
                holder.tvRoleTag.text = "销售"

            }

            3 -> {
                holder.tvRoleTag.text = "客户"

            }

            4 -> {
                holder.tvRoleTag.text = "虚拟用户"

            }

            5 -> {
                holder.tvRoleTag.text = "老师"

            }
        }

        holder.tvTimestamp.text = formatted1
        Glide.with(holder.ivAvatar).load(item.avatar).transform(CircleCrop()).into(holder.ivAvatar)
    }

    override fun getItemCount(): Int = messages.size

    fun append(item: MessageBean) {
        messages.add(item)
        notifyItemInserted(messages.size - 1)
    }

    fun setAll(items: List<MessageBean>) {
        messages.clear()
        messages.addAll(items)
        notifyDataSetChanged()
    }
} 